from pydoc_data.topics import topics
import threading
import time
import requests
import json
import paho.mqtt.client as mqtt
import os
from logs import Logging

logging = Logging(__name__)


class TDeviceConfig(object):
    def __init__(self) -> None:
        self.devConfig = {
            'version': 'device.v2022',
            'mqclient': {
                "host": "ai.seedlight.cn",
                "port": 31401,
                "uid": "admin",
                "pwd": "public",
                "pubTopic": "seedlight/pub/",
                "subTopic": "seedlight/sub/"
            },
            'tholds': {
                "t": 70,
            },
            'times': {
                "wait": 1,
                "run": 2,
                "input": 5,
                "upload": 300,
                "connect": 10,
                "takePhoto": 3600,
                "action": 3600
            },
            'filePath': {
                "sn": "/proc/cpuinfo",
                "deviceId": "/sys/class/mcu/system/serialno",
                "light": "/sys/class/gpio/gpio20/value",
                "brightness": "/sys/class/backlight/led-ir-pwm/brightness",
                "alarm": "/sys/class/gpio/gpio23/value",
                "volt": "/sys/class/ic/hlw8112/volt",
                "cur": "/sys/class/ic/hlw8112/cur",
                "curThrd": "/sys/class/ic/hlw8112/set_cur",
                "mac": "/sys/class/net/wlan0/address",
                "images": "/mnt/user/snapshot.jpg",
                "temp": "/sys/class/mcu/system/temp",
                "version": "/etc/version"
            },
            "thresholds": {
                "tmpLow": 60,
                "tmpHigh": 70
            }
        }


class TDeviceInfo(object):
    def __init__(self) -> None:
        self.sn = ""
        self.inputTime = 0
        self.light = 0
        self.volt = 0
        self.cur = 0
        self.curThrd = 0
        self.brightness = 0
        self.temp = 0.0
        self.mac = ''
        self.clientId = ''
        self.deviceId = ''
        self.version = ''
        self.lastInputTime = 0
        self.lastUploadTime = 0
        self.lastTakePhotoTime = 0
        self.lastConnectTime = 0
        self.lastActionTime = 0
        self.lightOpenFlag = 1
        self.lightOpenIndex = 0
        self.lastLightOpenTime = 0
        self.isOpenLight = 1  # 1允许打开光模组，不允许打开光模组
        # 新增报警功能
        self.lastAlarmTime = 0
        self.alarmFlag = 0

    def getUploadDatas(self, config):
        tempWarnFlag = 0
        if self.temp > config['thresholds']['tmpHigh']:
            tempWarnFlag = 1
        info = {
            "method": "u0",
            "params": {
                "light": self.light,
                "volt": self.volt,
                "cur": self.cur,
                "curThrd": self.curThrd,
                "brightness": self.brightness,
                "temp": self.temp,
                "tempWarnFlag": tempWarnFlag,
                "mac": self.mac,
                "deviceId": self.deviceId,
                "version": self.version
            }
        }
        res = json.dumps(info)
        return res


class TDevice(object):
    def __init__(self):
        print('init device...')
        self.isActive = False
        self.config = {}
        self.info = TDeviceInfo()
        self.mqClient = None
        self.isConnecting = 0
        self.durations = []
        self.imageFileTime = ''
        self.lightIndex = ''
        self.connectFlag = 0
        self.mqttConnectTime = 0
        self.mqttConnectTotal = 0

    def start(self):
        self.init()
        self.isActive = True
        thread_Input = threading.Thread(name='input', target=self.threadInput)
        thread_Input.setDaemon(True)
        thread_Input.start()
        thread_Uplpad = threading.Thread(name='upload', target=self.threadUpload)
        thread_Uplpad.setDaemon(True)
        thread_Uplpad.start()
        thread_TaksPhoto = threading.Thread(name='takephoto', target=self.threadTakephoto)
        thread_TaksPhoto.setDaemon(True)
        thread_TaksPhoto.start()
        thread_Connect = threading.Thread(name='connect', target=self.threadConnect)
        thread_Connect.setDaemon(True)
        thread_Connect.start()
        thread_Action = threading.Thread(name='action', target=self.threadAction)
        thread_Action.setDaemon(True)
        thread_Action.start()

        while True:
            time.sleep(2)

    # 初始化本设备
    def init(self):
        self.lightIndex = ''
        self.initDeviceId()
        self.initSn()
        self.initConfig()
        self.initDuration()
        self.getVersion()

    # 获取本设备序列号
    def initSn(self):
        try:
            fn = '/sys/class/mcu/system/serialno'
            if os.path.exists(fn):
                with open(fn, 'r') as f:
                    sn = f.readline().replace('\n', '')
            else:
                sn = ''
            time.sleep(2)
        except Exception as err:
            print("init sn faild.", err)
            logging.error('init sn faild. ' + str(err))
            sn = ""
        self.info.sn = sn

    # 获取本设备的CPU ID
    def initDeviceId(self):
        deviceId = '339d6b867f23f3e1'
        try:
            # fn = self.config['filePath']['sn']
            fn = '/proc/cpuinfo'
            if os.path.exists(fn):
                with open(fn, 'r') as f:
                    cpuinfo = f.readlines()
                    deviceId = cpuinfo[-1].split(':')[1].lstrip().replace('\n', '')
            time.sleep(2)
        except Exception as err:
            print("init deviceId faild.", err)
            logging.error('get deviceId faild.. ' + str(err))
            deviceId = ""
        self.info.deviceId = deviceId

    # 获取本设备固件版本号
    def getVersion(self):
        version = ''
        try:
            fn = self.config['filePath']['version']
            if os.path.exists(fn):
                with open(fn, 'r') as f:
                    version = f.readline().replace('\n', '')
            time.sleep(2)
        except Exception as err:
            print("init version faild.", err)
            logging.error('get sdk version faild.' + str(err))
            version = ""
        self.info.version = version

    # 获取本设备的配置参数
    def initConfig(self):
        try:
            configUrl = "https://ai.seedlight.cn:31000/config/" + self.info.sn + "_config.json"
            print(configUrl)
            response = requests.get(configUrl)
            contentJson = response.text
            config = json.loads(contentJson)
        except Exception as err:
            print('-------initConfig-------', err)
            logging.error('initConfig download fail, set init config! ')
            config = None
        if config == None:
            config = TDeviceConfig().devConfig
        self.config = config

    # 获取本设备的工作时段
    def initDuration(self):
        try:
            if self.info.sn:
                self.initSn()
            configUrl = "https://ai.seedlight.cn:31000/config/" + self.info.sn + "_plan.json"
            response = requests.get(configUrl)
            contentJson = response.text
            durations = list(json.loads(contentJson))
        except Exception as err:
            print('-------initDuration-------', err)
            logging.error('set init duration config!')
            durations = []
        if len(durations) == 0:
            durations = [{"start": 0, "len": 24 * 3600}]
        self.durations = durations

    def threadInput(self):
        print('start input thread...')
        try:
            while self.isActive:
                nowTm = int(time.time())
                dltTm = nowTm - self.info.lastInputTime
                flag = dltTm >= self.config['times']['input']
                if (flag):
                    self.info.lastInputTime = nowTm
                    try:
                        # print('input data', nowTm)
                        self.inputData()
                    except Exception as ee0:
                        print(ee0)
                time.sleep(self.config['times']['wait'])
        except Exception as err:
            print('-----------threadInput----------', err)

    def threadUpload(self):
        print('start upload thread...')
        try:
            while self.isActive:
                nowTm = int(time.time())
                dltTm = nowTm - self.info.lastUploadTime
                flag = dltTm >= self.config['times']['upload']
                curTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() + 28800))
                curDate = curTime[:10] + ' 00:00:00'
                startT = int(time.mktime(time.strptime(curDate, "%Y-%m-%d %H:%M:%S"))) - 8 * 3600
                if flag:
                    uploadFlag = False
                    self.info.lastUploadTime = nowTm
                    print('----------------------durations------------', self.durations)
                    for plan in self.durations:
                        if startT + plan['start'] <= nowTm and startT + plan['start'] + plan['len'] >= nowTm:
                            uploadFlag = True
                            self.info.lightOpenIndex += 1
                            if self.info.lightOpenIndex == 1:
                                self.info.lastLightOpenTime = nowTm
                                break
                    print('----------self.info.alarmFlag-----------', self.info.alarmFlag)
                    if self.info.alarmFlag == 1:
                        self.info.isOpenLight = 0
                        self.info.lightOpenFlag = 0
                        fn = self.config['filePath']['light']
                        with open(fn, 'w+') as f:
                            f.write('0')
                        time.sleep(5)
                    else:
                        if uploadFlag:
                            try:
                                # print('upload data', nowTm)
                                print('-------------lastLightOpenTime--------------',
                                      nowTm - self.info.lastLightOpenTime)
                                if 3600 <= nowTm - self.info.lastLightOpenTime < 4200:
                                    self.info.lightOpenFlag = 0
                                    self.info.isOpenLight = 0
                                elif nowTm - self.info.lastLightOpenTime >= 4200:
                                    self.info.lightOpenIndex = 0
                                    self.info.lightOpenFlag = 1
                                    self.info.isOpenLight = 1
                                elif nowTm - self.info.lastLightOpenTime < 3600:
                                    self.info.lightOpenFlag = 1
                                    self.info.isOpenLight = 1
                                if self.info.lightOpenFlag == 0:
                                    fn = self.config['filePath']['light']
                                    with open(fn, 'w+') as f:
                                        f.write('0')
                                    time.sleep(5)
                                else:
                                    fn = self.config['filePath']['light']
                                    with open(fn, 'w+') as f:
                                        f.write('1')
                                    time.sleep(5)
                                print('-----------running upload------------')
                            except Exception as ee0:
                                print(ee0)
                        else:
                            try:
                                self.info.lightOpenFlag = 1
                                if not self.lightIndex:
                                    lightVal = '0'
                                else:
                                    lightVal = self.lightIndex
                                fn = self.config['filePath']['light']
                                with open(fn, 'w+') as f:
                                    f.write(lightVal)
                                time.sleep(5)
                            except Exception as error:
                                print(error)
                        print('----------lightOpenFlag---------', self.info.lightOpenFlag)
                    self.uploadData()
                time.sleep(self.config['times']['wait'])
        except Exception as err:
            logging.error('threadUpload fail! ' + str(err))
            print('----------threadUpload----------', err)

    def threadTakephoto(self):
        print('start take photo thread...')
        try:
            while self.isActive:
                time.sleep(self.config['times']['wait'])
                nowTm = int(time.time())
                dltTm = nowTm - self.info.lastTakePhotoTime
                flag = dltTm >= self.config['times']['takePhoto']
                if flag:
                    self.info.lastTakePhotoTime = nowTm
                    try:
                        print('take photo', nowTm)
                        self.takePhoto()
                    except Exception as ee0:
                        print(ee0)
        except Exception as err:
            logging.error('threadTakephoto fail! ' + str(err))
            print('-----------threadTakephoto------------', err)

    def threadAction(self):
        print('start action thread...')
        try:
            while self.isActive:
                nowTm = int(time.time())
                dltTm = nowTm - self.info.lastActionTime
                flag = dltTm >= self.config['times']['action']
                if (flag):
                    self.info.lastActionTime = nowTm
                    try:
                        # print('action', nowTm)
                        # self.action()
                        pass
                    except Exception as ee0:
                        print(ee0)
                time.sleep(self.config['times']['wait'])
        except Exception as err:
            print('-----------threadAction------------', err)

    def threadConnect(self):
        print('start take photo thread...')
        try:
            while self.isActive:
                time.sleep(self.config['times']['wait'])
                nowTm = int(time.time())
                dltTm = nowTm - self.info.lastConnectTime
                clientIsConnected = self.isConnected()
                flag = dltTm >= self.config['times']['connect'] and self.isConnecting == 0 and clientIsConnected == 0
                if flag:
                    self.info.lastConnectTime = nowTm
                    try:
                        print('connect to mqtt server...', nowTm)
                        logging.info('connect to mqtt server...')
                        self.connectMqtt()
                    except Exception as ee0:
                        logging.error('connect to mqtt fail! ' + str(ee0))
                        print(ee0)
        except Exception as err:
            logging.error('connect to mqtt fail! ' + str(err))
            print('--------threadConnect--------', err)

    def isLightRunningTime(self, tm):
        res = False
        try:
            sec = int(tm) % (24 * 3600)
            items = list(filter(lambda s: s['start'] < sec and (s['start'] + s['len']) > sec, self.durations))
            res = len(items) > 0
        except Exception as err:
            print('--------isLightRunningTime----------', err)
        return res

    def isConnected(self):
        res = 0
        nowTm = int(time.time())
        durtion = nowTm - self.mqttConnectTime
        if durtion < 60 * 2:
            self.mqttConnectTime = nowTm
            self.mqttConnectTotal += 1
        if self.mqttConnectTotal > 10:
            logging.error('isConnected function start failed, restart app server after 5 seconds')
            time.sleep(5)
            os.system('bash /etc/init.sh')
        else:
            try:
                flag = self.mqClient != None and self.mqClient.is_connected()
                if flag:
                    res = 1
                    logging.info('self.mqClient value ' + str(self.mqClient))
                return res
            except Exception as err:
                res = 0
                logging.error('connect to mqtt fail! ' + str(err))
                print('-------isConnected--------', err)
                return res

    def connectMqtt(self):
        print('start connect mqtt...')
        try:
            if self.isConnecting == 1:
                pass
            else:
                self.isConnecting = 0
                try:
                    self.info.clientId = self.info.deviceId + '_' + time.strftime('%Y%m%d%H%M%S',
                                                                                  time.localtime(time.time()))
                    self.mqClient = mqtt.Client(self.info.clientId)
                    userName = self.config['mqclient']['uid']
                    pwd = self.config['mqclient']['pwd']
                    host = self.config['mqclient']['host']
                    port = self.config['mqclient']['port']
                    self.mqClient.username_pw_set(userName, pwd)
                    content = json.dumps({
                        'method': 'u10',
                        'params': {
                            'status': 'off',
                            'deviceId': self.info.deviceId,
                            'clientId': self.info.clientId
                        }
                    })
                    logging.info('mqtt offline ' + content)
                    self.mqClient.will_set(self.config['mqclient']['pubTopic'] + self.info.sn, content)
                    self.mqClient.connect(host, int(port), 60)
                    self.mqClient.on_connect = self.on_connect
                    self.mqClient.on_message = self.on_message
                    # self.mqClient.reconnect_delay_set(min_delay=1, max_delay=10)
                    # self.mqClient.connect_fail_callback()
                    self.mqClient.on_disconnect = self.on_disconnect
                except Exception as e0:
                    logging.error('connect to mqtt fail! ' + str(e0))
                    print(e0)
                    self.isActive = True
                    self.isConnecting = 0
                    logging.error('connectMqtt failed，restart app server after 3 seconds！！！')
                    time.sleep(3)
                    os.system('bash /etc/init.sh')
                    # self.mqttConnectTotal += 1
                    # if self.mqttConnectTotal <= 10:
                    #     time.sleep(self.mqttConnectTotal * 5 * 60)
                    #     logging.error(
                    #         'connectMqtt failed' + str(e0) + ',connectMqtt count ' + str(self.mqttConnectTotal))
                    #     self.connectMqtt()
                    # else:
                    #     logging.info('reboot device ...')
                    #     os.system('reboot')
                self.mqClient.loop_forever()
        except Exception as err:
            logging.error('connectMqtt  error ' + str(err))
            print('----------connectMqtt-----------', err)

    def on_connect(self, client, userdata, flags, rc):
        try:
            self.isConnecting = 0
            if rc == 0:
                print('connect mq server success')
                subTopic = self.config['mqclient']['subTopic']
                subTopic = subTopic + self.info.sn
                self.mqClient.subscribe(subTopic)
                print('subscribe ', subTopic)
                content = json.dumps({
                    'method': 'u10',
                    'params': {
                        'status': 'on',
                        'deviceId': self.info.deviceId,
                        'clientId': self.info.clientId
                    }
                })
                logging.info('on_connect success' + content)
                self.mqClient.publish(self.config['mqclient']['pubTopic'] + self.info.sn, content)
                self.uploadData()
                self.takePhoto()
            else:
                print("Connected with result code " + str(rc))
                print('mqtt server connection failed')
        except Exception as e:
            logging.error('on_connect  error ' + str(e))
            print('-----------on_connect---------', e)

    def on_disconnect(self, client, userdata, rc):
        logging.info("unexpected disconnection rc = " + str(rc))
        try:
            # self.isConnecting = 0
            self.re_connect()
        except Exception as e:
            logging.error('on_disconnect failed,' + str(e) + ' ,restart app server after 3 seconds!!!')
            time.sleep(3)
            os.system('bash /etc/init.sh')

    def re_connect(self):
        try:
            # self.mqClient.reconnect()
            # self.mqClient.loop_forever()
            logging.error('app server disconnect,restart app server after 5 seconds!!!')
            time.sleep(5)
            os.system('bash /etc/init.sh')
        except Exception as e:
            self.isConnecting = 0
            logging.error('network connect failed ' + str(e))
            print(e)
            time.sleep(5)
            logging.info('restart app server')
            os.system('bash /etc/init.sh')
            # time.sleep(60)
            # self.re_connect()

    def setBrightness(self, value):
        try:
            fn = self.config['filePath']['brightness']
            with open(fn, 'w+') as f:
                f.write(value)
            return 'ok'
        except Exception as e0:
            logging.error('setBrightness failed' + str(e0))
            print('--------setBrightness--------', e0)
            return None

    def setLightStatus(self, value):
        try:
            fn = self.config['filePath']['light']
            with open(fn, 'w+') as f:
                f.write(value)
            return 'ok'
        except Exception as e0:
            print('--------setLightStatus--------', e0)
            logging.error('setLightStatus failed' + str(e0))
            return None

    def setAlarm(self, value):
        try:
            fn = self.config['filePath']['alarm']
            with open(fn, 'w+') as f:
                f.write(value)
        except Exception as e0:
            logging.error('setAlarm failed' + str(e0))
            print('--------setAlarm--------', e0)

    def setCurVal(self, value):
        try:
            if 500 <= int(value) <= 1500:
                fn = self.config['filePath']['curThrd']
                with open(fn, 'w+') as f:
                    f.write(value)
            return 'ok'
        except Exception as e0:
            logging.error('setCurVal failed' + str(e0))
            print('--------setCurVal--------', e0)
            return None

    def uploadConfig(self, method):
        try:
            flag = self.isConnected()
            if flag:
                params = {}
                if method == 'u3':
                    params = self.durations
                elif method == 'u4':
                    params = self.config
                content = json.dumps({
                    'method': method,
                    'params': params
                })
                topic = self.config['mqclient']['pubTopic'] + self.info.sn
                self.mqClient.publish(topic, content)
        except Exception as e0:
            print('--------uploadConfig--------', e0)

    def uploadImage(self):
        try:
            flag = self.isConnected()
            url = 'https://ai.seedlight.cn:31000/images/'
            if flag:
                content = {'method': 'u5', 'params': {
                    'imageFileTime': self.imageFileTime,
                    'imageUrl': url + self.info.sn + '_' + str(self.imageFileTime) + '.jpg'
                }}
                payload = json.dumps(content)
                topic = self.config['mqclient']['pubTopic'] + self.info.sn
                logging.info('uploadImage ' + payload)
                self.mqClient.publish(topic, payload)
        except Exception as e0:
            print('--------uploadImage--------', e0)

    def on_message(self, client, userdata, msg):
        try:
            data = json.loads(msg.payload.decode("utf-8"))
            logging.info('receive issue：' + json.dumps(data))
            if data['method'] == 'd0':
                # call command
                cmdLine = data['params']['cmd']
                os.system(cmdLine)
                time.sleep(3)
                self.uploadData('u1')
            elif data['method'] == 'd1':
                # reset init
                self.init()
            elif data['method'] == 'd2':
                # manual get realdata
                resMethod = 'u1'
                self.uploadData(resMethod)
            elif data['method'] == 'd3':
                # set brightness
                value = data['params']['value']
                res = self.setBrightness(value)
                if res:
                    self.inputData()
                    resMethod = 'u1'
                    self.uploadData(resMethod)
            elif data['method'] == 'd4':
                # read duration config
                self.uploadConfig('u3')
            elif data['method'] == 'd5':
                # take photo
                self.takePhoto()
            elif data['method'] == 'd6':
                # set light status
                value = data['params']['value']
                self.lightIndex = value
                res = self.setLightStatus(value)
                time.sleep(3)
                if res:
                    self.inputData()
                    resMethod = 'u1'
                    self.uploadData(resMethod)
            elif data['method'] == 'd7':
                self.initDuration()
            elif data['method'] == 'd8':
                # read network config
                self.uploadConfig('u4')
            elif data['method'] == 'd9':
                # read network config
                value = data['params']['value']
                res = self.setCurVal(value)
                time.sleep(3)
                if res:
                    self.inputData()
                    resMethod = 'u1'
                    self.uploadData(resMethod)
            print('rec:', data)
        except Exception as e:
            print('--------on_message--------', e)

    def inputData(self):
        try:
            params = result = {
                'light': 0,
                'brightness': 0,
                'volt': 0,
                'cur': 0,
                'temp': 0.0,
                'curThrd': 0,
                'mac': ''
            }
            for i in params.keys():
                fn = self.config['filePath'][i]
                flag = os.path.exists(fn)
                if flag:
                    if i == 'mac':
                        with open(fn, 'r') as f:
                            result[i] = f.readline().replace('\n', '')
                    else:
                        if i != 'temp':
                            with open(fn, 'r') as f:
                                result[i] = int(f.readline().replace('\n', ''))
                        elif i == 'temp':
                            with open(fn, 'r') as f:
                                result[i] = float(f.readline().replace('\n', ''))
            # for k in result.keys():
            # self.info[k] = result[k]
            self.info.light = result['light']
            self.info.volt = result['volt']
            self.info.cur = result['cur']
            self.info.curThrd = result['curThrd']
            self.info.brightness = result['brightness']
            self.info.temp = result['temp']
            self.info.mac = result['mac']
            self.info.inputTime = int(time.time())
            self.checkWarn()
        except Exception as err:
            print('inputData failed', err)
            logging.error('inputData failed' + str(err))
            print('--------inputData--------', err)

    def checkWarn(self):
        try:
            print('temp', self.info.temp)
            print('tholds', self.config['tholds']['t'])
            if self.info.temp > self.config['tholds']['t']:
                self.setAlarm('1')
                self.info.alarmFlag = 1
                self.setLightStatus('0')
            if self.info.alarmFlag == 1:
                if self.info.temp <= self.config['tholds']['t'] * 0.7:
                    self.info.alarmFlag = 0
                    self.setAlarm('0')
        except Exception as err:
            print('---------checkWarn----------', err)

    def uploadData(self, method='u0'):
        try:
            flag = self.isConnected()
            if flag:
                content = self.getUploadDatas(self.config, method)
                topic = self.config['mqclient']['pubTopic'] + self.info.sn
                logging.info('update real data： ' + content)
                self.mqClient.publish(topic, content)
        except Exception as err:
            logging.error('uploadData failed ' + str(err))
            print('--------uploadData--------', err)

    def getUploadDatas(self, config, method):
        tempWarnFlag = 0
        if self.info.temp > config['thresholds']['tmpHigh']:
            tempWarnFlag = 1
        info = {
            "method": method,
            "params": {
                "deviceId": self.info.deviceId,
                "light": self.info.light,
                "volt": self.info.volt,
                "cur": self.info.cur,
                "curThrd": self.info.curThrd,
                "brightness": self.info.brightness,
                "temp": self.info.temp,
                "tempWarnFlag": tempWarnFlag,
                "isOpenLight": self.info.isOpenLight,
                "mac": self.info.mac,
                "realTime": int(time.time()),
                "version": self.info.version,
                "clientId": self.info.clientId
                # "status": 'on'
            }
        }
        if tempWarnFlag == 1:
            info['method'] = 'u2'
        res = json.dumps(info)
        return res

    def action(self):
        try:
            lightFlag = self.info.light
            isOnDurationFlag = self.isLightRunningTime(time.time())
            isOffDurationFlag = not isOnDurationFlag
            temp = self.info.temp

            onFlag = lightFlag == 0 and isOnDurationFlag and temp < self.config['thresholds']['tmpLow']
            offFlag = (lightFlag == 1 and temp >= self.config['thresholds']['tmpHigh']) or (
                    lightFlag == 1 and isOffDurationFlag)
            fn = self.config['filePath']['light']
            if self.lightIndex == '':
                if onFlag:
                    with open(fn, 'w+') as f:
                        f.write('1')
                elif offFlag:
                    with open(fn, 'w+') as f:
                        f.write('0')
            if offFlag or onFlag:
                self.inputData()
                self.uploadData()
                time.sleep(5)
                self.takePhoto()

        except Exception as err:
            print('--------action--------', err)

    def takePhoto(self):
        try:
            fn = self.config['filePath']['images']
            self.inputData()
            if self.info.brightness == 0:
                self.setBrightness('185')
            time.sleep(5)
            os.system('message_tools CatchOnePic')
            time.sleep(5)
            self.imageFileTime = int(time.time())
            imageFileName = self.info.sn + '_' + str(self.imageFileTime) + '.jpg'
            print(imageFileName)
            logging.info('img name ' + imageFileName)
            if os.path.exists(fn):
                cmd = ''
                if os.path.exists(r'/etc/uploadImg.sh'):
                    cmd = 'bash /etc/uploadImg.sh {filename}'.format(filename=imageFileName)
                elif os.path.exists(r'/uploadImg.sh'):
                    cmd = 'bash /uploadImg.sh {filename}'.format(filename=imageFileName)
                os.system(cmd)
                time.sleep(5)
                self.uploadImage()
                time.sleep(3)
                self.setBrightness('0')
        except Exception as err:
            logging.error('takePhoto faild. ' + str(err))
            print('--------takePhoto--------', err)

    # 执行命令行
    def operateCommand(self, data):
        try:
            if data:
                print(data)
                res = os.popen(data['params'])
                print(res.readlines())
                return 'success'
            else:
                return None
        except Exception as e:
            print('--------operateCommand--------', e)
            return None


if __name__ == '__main__':
    device = TDevice()
    # timing = {
    #     "params": "bash /data/server/zkxinhe/device/timing.sh"
    # }
    # device.operateCommand(timing)
    device.start()
